package com.example.webbrowser.Adapter;

import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.example.webbrowser.Database.WebHistoryDao;
import com.example.webbrowser.Entity.WebHistory;
import com.example.webbrowser.R;
import com.example.webbrowser.WebViewActivity;

import org.w3c.dom.Text;

import java.util.List;

public class HistoryAdapter extends ArrayAdapter<WebHistory>
{
    // 子项布局的id
    private int resourceId;
    private WebHistoryDao webHistoryDao;
    private List<WebHistory> dataList;
    private Intent intent;
    private Context context;

    public HistoryAdapter(@NonNull Context context,  int textViewResourceId, @NonNull List<WebHistory> objects) {
        super(context,  textViewResourceId, objects);
        this.context = context;
        webHistoryDao = new WebHistoryDao(getContext());
        intent = new Intent(getContext(), WebViewActivity.class);
        resourceId = textViewResourceId;
        dataList = objects;
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        View view = null;
        //布局不变，数据变

        //如果缓存为空，我们生成新的布局作为1个item
        if (convertView == null) {
            view = LayoutInflater.from(getContext()).inflate(resourceId, parent, false);
        } else {
            view = convertView;
        }
        //获取当前项的实例
        WebHistory history = getItem(position);
        TextView titleView = (TextView) view.findViewById(R.id.history_title);
       // TextView historyView = (TextView) view.findViewById(R.id.history_url);
        titleView.setText(history.getTitle());
        //historyView.setText(history.getUrl());

        //实现删除按钮
        View button = view.findViewById(R.id.history_delete);
        button.setOnClickListener(v->{
            //System.out.println("你点击了删除历史按钮"+history.getId());
            webHistoryDao.delete(history.getId());
            dataList.remove(position);
            notifyDataSetChanged();

        });

        //实现跳转按钮
        View viewItem = view.findViewById(R.id.history_item);
        viewItem.setOnClickListener(v->{
             Log.i("info:", "你点击了跳转按钮\"" + position);
            //System.out.println("你点击了跳转按钮");
            String url = history.getUrl();
            intent.putExtra("web_url",url);
            context.startActivity(intent);
        });

        return view;
    }


}
